import React, { PureComponent } from 'react';
import { createForm } from 'rc-form'
import DocumentTitle from 'react-document-title';
import { withRouter } from 'react-router-dom';
import arrayTreeFilter from 'array-tree-filter';

import reqeust from '@service';
import { store } from '@store';


import { EditAddressStyle } from './style';
import { InputItem, List, Picker, Toast } from 'antd-mobile';

import {
  fetchAddressAction
} from '@store/actionCreators'

const AMap = window.AMap

class EditAddress extends PureComponent {
  state = {
    visible: false,
    name: '',
    phone: '',
    detailAddress: '',
  }

  uniacid = store.getState().appConfig.uniacid


  requestConfig = {
    getAddressInfo: {
      data: {
        action: 'address_show',
        uniacid: this.uniacid,
        id: ''
      }
    },
    updateAddress: {
      data: {
        action: 'addAddress',
        uniacid: this.uniacid,
        id: ''
      }
    }
  }

  componentDidMount() {
    let auto = new AMap.Autocomplete({
      city: '全国',
      input: "tipinput"
    });
    AMap.event.addListener(auto, "select", (e) => {
      console.log('选择地址', e)
      // setState(e.poi)
    });//注册监听，当选中某条记录时会触发


    this.district = this.getDistrict();

    let addressId = this.props.match.params.id

    if (addressId !== 'add') {
      this.requestConfig.getAddressInfo.data.id = addressId
      this.requestConfig.updateAddress.data.id = addressId

      reqeust(this.requestConfig.getAddressInfo).then(res => {
        let data = res.data[0]
        let detailAddress = data.detailed_address
        let phone = data.tel
        let name = data.name
        let pickerValue = [data.province, data.city, data.county]

        this.setState({
          phone,
          detailAddress,
          name,
          pickerValue
        })
      })
    }
  }

  render() {
    const { name, phone, detailAddress } = this.state;
    const { getFieldProps } = this.props.form;
    return (
      <>
        <DocumentTitle title={this.props.route.title} />
        <EditAddressStyle>
          <div className="main">
            <List>
              {/* <div className="select-address">
                <div className="into-address" onClick={() => { this.props.history.push('/location/' + this.props.match.params.id) }}>
                  选择地址
                </div>
              </div> */}
              <InputItem
                placeholder={name !== '' ? name : "请输入真实姓名"}
                {...getFieldProps('name')}
              >
                收货人
                </InputItem>
              <InputItem
                placeholder={phone !== '' ? phone : "请输入手机号码"}
                {...getFieldProps('phone')}
                maxLength={11}
              >
                手机号码
              </InputItem>

              <InputItem
                placeholder="请选择所在地区"
                onClick={() => this.setState({ visible: true })}
                editable={false}
                value={this.getSel()}
                type="text"
              >
                所在地区
              </InputItem>


              <InputItem
                placeholder={detailAddress !== '' ? detailAddress : "请输入详细地址"}
                {...getFieldProps('detailAddress')}
                type="text"
              >
                详细地址
                </InputItem>
            </List>

            <button className="bottom" onClick={e => { this.submit() }}>
              保存
            </button>

          </div>


          <div className=""
            style={{
              // marginTop: '5rem'
            }}
          >
            <Picker
              visible={this.state.visible}
              data={this.district}
              value={this.state.pickerValue}
              onChange={v => this.setState({ pickerValue: v })}
              onOk={() => this.setState({ visible: false })}
              onDismiss={() => this.setState({ visible: false })}
            >
              {/* <List.Item extra={this.getSel()} onClick={() => this.setState({ visible: true })}>
                所在地区
            </List.Item> */}
            </Picker>
          </div>



        </EditAddressStyle>
      </>
    );
  }




  submit() {
    let props = this.props
    props.form.validateFields({ force: true }, (error) => {
      if (!error) {
        let area = this.state.pickerValue
        const { name, phone, detailAddress } = props.form.getFieldsValue();
        let update = this.requestConfig.updateAddress.data;
        update.name = name || this.state.name;
        update.tel = phone || this.state.phone;
        update.detailed_address = detailAddress || this.state.detailAddress;
        update.province = area[0];
        update.city = area[1];
        update.county = area[2];
        update.type = '';
        update.is_default = '';


        if (update.name === '') {
          Toast.info('请填写收货人', 1)
        } else if (update.phone === '') {
          Toast.info('请填写手机号码', 1)
        } else if (update.detailAddress === '') {
          Toast.info('请填写详细地址', 1)
        } else {
          reqeust(this.requestConfig.updateAddress).then(res => {
            if (res.status === 200) {
              store.dispatch(fetchAddressAction)
              Toast.success(res.msg, 1)
              this.props.history.replace('/myaddress/editAddress')
            } else {
              Toast.fail(res.msg, 2)
            }
          })
        }

      } else {
        console.log('Validation failed');
      }
    });
  }

  getSel() {
    const value = this.state.pickerValue;
    if (!value) {
      return '';
    }
    const treeChildren = arrayTreeFilter(this.district, (c, level) => c.value === value[level]);
    console.log(treeChildren)
    return treeChildren.map(v => v.label).join(',');
  }

  getDistrict() {
    // 获取选择地区数据
    let districtData = require('./location');

    let antdDistrict = [];
    Object.keys(districtData).forEach((index) => {
      let itemLevel1 = {};
      let itemLevel2 = {};
      itemLevel1.value = districtData[index].code;
      itemLevel1.label = districtData[index].name;
      itemLevel1.children = [];
      let data = districtData[index].cities;
      Object.keys(data).forEach((index) => {
        itemLevel2.value = data[index].code;
        itemLevel2.label = data[index].name;
        itemLevel2.children = [];
        let data2 = data[index].districts;
        let itemLevel3 = {};
        itemLevel3.children = [];
        Object.keys(data2).forEach((index) => {
          itemLevel3.value = index;
          itemLevel3.label = data2[index];
          itemLevel2.children.push(itemLevel3);
          itemLevel3 = {};
        });
        itemLevel1.children.push(itemLevel2);
        itemLevel2 = {};
      });
      antdDistrict.push(itemLevel1)
    });

    return antdDistrict
  }
}

const EditAddressWrapper = createForm()(EditAddress);




export default withRouter(EditAddressWrapper);